package com.shujia.day14;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Scanner;

public class Code15WriterTest {
    public static void main(String[] args) throws IOException {
        /*
            键盘录入5个学生信息(姓名,语文成绩,数学成绩,英语成绩),按照总分从高到低存入文本文件

            分析：
                ① 创建一个Scanner 录入五个学生对象
                ② TreeSet可以对数据进行排序 也可以放入List中进行存储 存储完成后需要对其进行排序
                ③ 对排好顺序的对象转成字符串 再去写入到文本文件中
         */

        Scanner scanner = new Scanner(System.in);
        ArrayList<HStudent> hStudents = new ArrayList<>();

        for (int i = 0; i < 2; i++) {
            System.out.println("请输入姓名：");
            String name = scanner.next();
            System.out.println("请输入语文成绩:\n");
            int chinese = scanner.nextInt();
            System.out.println("请输入数学成绩");
            int math = scanner.nextInt();
            System.out.println("请输入英语成绩");
            int english = scanner.nextInt();
            hStudents.add(new HStudent(name, chinese, math, english));
        }

        // 通过集合工具类对List中数据进行排序
        //  工具类sort排序方式有两种 第一种要求对存储的元素继承Comparable接口 第二种传入一个Comparator的接口实现类对象
        Collections.sort(hStudents, new Comparator<HStudent>() {
            @Override
            public int compare(HStudent o1, HStudent o2) {
                // o1表示当前对象  o2表示集合中的对象
                int o1Score =  o1.chinese + o1.english + o1.math;
                int o2Score =  o2.chinese + o2.english + o2.math;
                return -(o1Score - o2Score == 0 ? o1.name.compareTo(o2.name): o1Score - o2Score);
            }
        });

        // 使用 BufferedWriter 字符缓冲流
        BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter("data/studentSort.txt"));
        for (HStudent hStudent : hStudents) {
            bufferedWriter.write(hStudent.toString());
            bufferedWriter.newLine();
            bufferedWriter.flush();
        }
        bufferedWriter.close();

    }


}

class HStudent {
    String name;
    int chinese;

    int math;

    int english;

    public HStudent() {
    }

    public HStudent(String name, int chinese, int math, int english) {
        this.name = name;
        this.chinese = chinese;
        this.math = math;
        this.english = english;
    }


    @Override
    public String toString() {
        return "HStudent{" +
                "name='" + name + '\'' +
                ", chinese=" + chinese +
                ", math=" + math +
                ", english=" + english +
                '}';
    }
}